Variables and Naming Conventions
1. Variable Declaration & Assignments
A variable stores data values in memory, which can be referenced and manipulated in the program. Variables in Python are dynamically typed, meaning you don’t need to declare their data type explicitly.
x = 10
y = "Hello"
Python allows you to assign multiple variables in a single line. Just separate the variables with a comma, and the right-hand side values with a comma as well.
Ensure the number of variables matches the number of values you're assigning.
msg1, msg2 = "Hello", "World"
#equivalent to`
msg1 = "Hello"
msg2 = "World"
We can also use multiple assignments to swap the values of variables:
msg1, msg2 = "Hello", "World" # msg1 = "Hello", msg2 = "World"
msg1, msg2 = msg2, msg1 # msg1 = "World", msg2 = "Hello"
2. Variable Reassignment
Variables can change their value, this is called reassigning a variable.
x = 5
x = "Now I'm a string"
Python allows you to reassign different types of values to the same variable, but this can sometimes
3. Variable Naming & Convention
There are some strict rules for naming variables, if you break any of these rules it will cause an error:
- Variable names can only contain letters, numbers, and underscores.
- Variable names can't start with a number.
- Variable names can't contain spaces.
- Variable names can't be the same as Python keywords like
for,if, etc.
my_number = 5
my_string = "text"
More than having good variable names, it's important to follow naming conventions. There are several different naming conventions such as:
- Camel Case: The first letter of each word is capitalized except for the first word. For example,
myVariableName. - Snake Case: Words are separated by underscores. For example,
my_variable_name. - Pascal Case: The first letter of each word is capitalized. For example,
MyVariableName.
In Python, we typically use the snake case. This means we use underscores (_) to separate words in variable names.
lead to confusion. Keep an eye on the types you're working with.
4. Variable Types
Variables in Python can hold different types of data, such as integers, decimal numbers (aka floating-point numbers), strings, booleans, lists, and more. Python will infer the type based on the value assigned.
- A variable is an integer type when it holds a whole number value.
- A variable is a floating-point number type when it holds a decimal number value.
- A variable is a boolean type when it holds a
True